import { loginApi, getInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || null,
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    // 存取本地token
    setToken(data)
  },
  removeToken(state) {
    state.token = null
    // 删除本地token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async loginAction(store, data) {
    const res = await loginApi(data)
    // console.log(res)
    store.commit('setToken', res)
  },
  // 通过接口函数获取用户信息
  async getUserInfo(store) {
    const res = await getInfoApi()
    store.commit('setUserInfo', res)
  },
  // token失效退出
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
